<?php
/**
 * Created by PhpStorm.
 * User: 65736
 * Date: 2019/4/3 0003
 * Time: 14:01
 */

namespace app\common\model\wechat;


use app\common\model\CommonModel;

class WeChatUserMiniModel extends CommonModel
{
    /**
     * 数据库配置
     *
     * @var string
     */
    protected $connection = 'db_config_wechat';

    /**
     * 表名称
     *
     * @var string
     */
    protected $table = "wechat_user_mini";


    /**
     * 初始化方法
     * {@inheritDoc}
     * @see CommonModel::initialize()
     */
    protected function initialize()
    {
        parent::initialize();
        // 加入唯一索引
        $this->unique_fields[] = 'open_id';
    }

    /**
     * 查询并添加用户信息
     * @param $open_id
     * @param $data
     * @return array|bool|static
     * @throws \think\Exception
     */
    public function get_or_add($open_id, $data)
    {
        $user_data = $this->get_data_by_unique_key("open_id", $open_id);

        if ($user_data) {
            return $user_data;
        }

        $res = $this->add_data($data);
        if (!$res) {
            return false;
        }

        $data['id'] = $res;
        return $data;
    }
}